package com.example.mvvmapplication.view

import android.os.Bundle
import android.util.Log
import android.view.View
import androidx.appcompat.app.AppCompatActivity
import androidx.lifecycle.ViewModelProvider
import androidx.lifecycle.lifecycleScope
import androidx.recyclerview.widget.LinearLayoutManager
import com.example.mvvmapplication.R
import com.example.mvvmapplication.adapter.SellAdapter
import com.example.mvvmapplication.domain.MapData
import com.example.mvvmapplication.viewmodel.OnSellViewModel
import com.lcodecore.tkrefreshlayout.RefreshListenerAdapter
import com.lcodecore.tkrefreshlayout.TwinklingRefreshLayout
import kotlinx.android.synthetic.main.activity_main.*
import kotlinx.coroutines.*

class OnSellActivity : AppCompatActivity() {

    private val mainScope = MainScope()

    private val mViewModel by lazy {
        ViewModelProvider(this).get(OnSellViewModel::class.java)
    }

    private val mSellAdapter by lazy {
        SellAdapter(R.layout.item_sell_rv, mutableListOf<MapData>())
    }

    companion object {
        private const val TAG = "OnSellActivity"
    }

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)

        initView()
        initObserver()

        initCoroutines()

    }


    // 耗时函数 1
    private suspend fun getData() = withContext(Dispatchers.IO) {
        // 假设这个函数比较耗时，需要放在后台
        return@withContext "hen_coder"
    }

    // 耗时函数 2
    private suspend fun processData(data: String): String {
        return withContext(Dispatchers.IO) {
            // 假设这个函数也比较耗时，需要放在后台
            return@withContext data.split("_") // 把 "hen_coder" 拆成 ["hen", "coder"]
                .map { it.capitalize() } // 把 ["hen", "coder"] 改成 ["Hen", "Coder"]
                .reduce { acc, s -> acc + s } // 把 ["Hen", "Coder"] 改成 "HenCoder"
        }
    }

    private fun initCoroutines() {
        // 原始使用   没办法释放 有缺陷
        GlobalScope.launch(Dispatchers.Main) {
            withContext(Dispatchers.IO) {
                Log.d(TAG, "initCoroutines: " + Thread.currentThread().name)
            }
            Log.d(TAG, "initCoroutines: " + Thread.currentThread().name)


            Log.d(TAG, "initCoroutines: " + processData(getData()))
        }

        // 绑定到了lifecycle   强烈推荐
        lifecycleScope.launch {
            Log.d(TAG, "initCoroutines: lifecycleScope.launch")
        }

        //
        mainScope.launch {
            // 等同于  GlobalScope.launch(Dispatchers.Main){}
        }
    }

    override fun onDestroy() {
        // 取消 协程
        mainScope.cancel()
        super.onDestroy()
    }

    override fun onStart() {
        super.onStart()
        Log.d(TAG, "onStart: ")
    }

    override fun onResume() {
        super.onResume()
        Log.d(TAG, "onResume: ")
    }

    /**
     * 观察数据
     */
    private fun initObserver() {
        mViewModel.apply {
            // 2020/11/3 内容列表更新
            contentList.observe(this@OnSellActivity) {
//                mSellAdapter.setNewInstance(it)
                mSellAdapter.addData(it)
            }

            // 请求状态
            loadState.observe(this@OnSellActivity) {
                when (it) {
                    OnSellViewModel.LoadState.None -> {
                        loadErrorView.visibility = View.GONE
                        loadLoadingView.visibility = View.GONE
                    }
                    OnSellViewModel.LoadState.Loading -> {
                        loadErrorView.visibility = View.GONE
                        loadLoadingView.visibility = View.VISIBLE
                    }
                    OnSellViewModel.LoadState.Success -> {
                        loadErrorView.visibility = View.GONE
                        loadLoadingView.visibility = View.GONE
                        contentRefreshMain.finishLoadmore()
                    }
                    OnSellViewModel.LoadState.Error -> {
                        loadErrorView.visibility = View.VISIBLE
                        loadLoadingView.visibility = View.GONE
                    }
                    OnSellViewModel.LoadState.LOADER_MORE_ERROR -> {
                        contentRefreshMain.finishLoadmore()
                    }
                    OnSellViewModel.LoadState.LOADER_MORE_EMPTY -> {
                        contentRefreshMain.finishLoadmore()
                    }
                    OnSellViewModel.LoadState.LOADER_MORE_SUCCESS -> {
                        contentRefreshMain.finishLoadmore()
                    }

                    else -> {
                        loadErrorView.visibility = View.GONE
                        loadLoadingView.visibility = View.GONE
                    }
                }
            }
        }.loadContent()
    }

    /**
     * 初始化view
     */
    private fun initView() {
        // 设置 rv 为 LinearLayoutManager
        rvMainSellView.run {
            val linearLayoutManager = LinearLayoutManager(this@OnSellActivity)
            linearLayoutManager.orientation = LinearLayoutManager.VERTICAL
            layoutManager = linearLayoutManager
            adapter = mSellAdapter
        }

        loadErrorView.setOnClickListener {
            mViewModel.loadContent()
        }

        contentRefreshMain.run {
            setEnableLoadmore(true)
            setEnableRefresh(false)
            setEnableOverScroll(true)
            setOnRefreshListener(object : RefreshListenerAdapter() {
                override fun onLoadMore(refreshLayout: TwinklingRefreshLayout?) {
                    // TODO: 2020/11/3 加载更多
                    mViewModel.loadMore()
                }
            })
        }
    }
}
